import { action, observable, computed } from 'mobx'

export interface Options<T> {
  value: T
  onChange?: (value: T, prevValue: T) => void
}

export class CheckToRadioState<T> {
  options: Options<T>
  @observable
  value: T

  constructor(options: Options<T>) {
    this.value = options.value
    this.options = options
  }

  @computed.struct
  get checkedList() {
    return [this.value]
  }

  @action
  change = (value: T[]) => {
    const newValue = this.toValue(value)
    if (this.options.onChange) this.options.onChange(newValue, this.value)

    if (newValue !== this.value) this.value = newValue

    return newValue
  }

  toValue = (value: T[]) => {
    if (value.length == 0) return this.value
    const newList = value.filter(item => item !== this.value)
    if (newList.length == 0) return this.value
    const newVal = newList[0]
    return newVal
  }
}

// export default function create<T>(options: Options<T>) {
//   return new CheckToRadioState<T>(options)
// }
